package cn.sq.musicserver.plug.model.wpmusicapi;

import cn.sq.musicserver.config.SQConstant;
import cn.sq.musicserver.exception.PlugError;
import cn.sq.musicserver.music.entity.DownloadParam;
import cn.sq.musicserver.music.entity.SqMusic;
import cn.sq.musicserver.music.service.impl.SqMusicServiceImpl;
import cn.sq.musicserver.plug.entity.PlugLyicResult;
import cn.sq.musicserver.plug.entity.PlugSearchResult;
import cn.sq.musicserver.plug.hander.MusicInfoSearc;
import cn.sq.musicserver.plug.model.jsososo.entity.LyricParam;
import cn.sq.musicserver.plug.model.wpmusicapi.constants.WPMusicApiConstantQQ;
import cn.sq.musicserver.plug.model.wpmusicapi.kg.WPKGMusicApiService;
import cn.sq.musicserver.plug.model.wpmusicapi.kw.WPKWMusicApiService;
import cn.sq.musicserver.plug.model.wpmusicapi.param.WPParam;
import cn.sq.musicserver.plug.model.wpmusicapi.qq.WPQQMusicApiService;
import cn.sq.musicserver.plug.model.wpmusicapi.qq.entity.*;
import cn.sq.musicserver.set.entity.SqSet;
import cn.sq.musicserver.set.service.impl.SqSetServiceImpl;
import cn.sq.musicserver.utils.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.classgraph.utils.Join;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 2021/3/29
 * Time: 11:44
 * Description:
 */
@Slf4j
@Component
public class WPHander extends MusicInfoSearc {
    @Autowired
    WPQQMusicApiService qqMusicApiService;
    @Autowired
    WPKGMusicApiService kgMusicApiService;
    @Autowired
    WPKWMusicApiService kwMusicApiService;
    @Autowired
    SqSetServiceImpl setService;
    @Autowired
    SqMusicServiceImpl musicService;

    @Override
    public String PlugName() {
        return "WPMuiscApi";
    }

    @Override
    public String Plugversion() {
        return "1.0";
    }

    @Override
    public PlugSearchResult musicInfoSearc(Integer pagersize, Integer pageindex, String Keywords, File music, List<SqSet> set, Map<String, String> data) throws PlugError {
            //查询通道 qq，kg，kw
            String queue = data.get("queue");
        ArrayList<String> strings = new ArrayList<>();
        strings.add("qq");
        strings.add("kg");
        strings.add("kw");
        strings.add("QQ");
        strings.add("KG");
        strings.add("KW");
        boolean contains = strings.contains(queue);
        if (!contains) {
            throw new PlugError("插件通道错误，通道支持QQ，KG,KW");
        }
        PlugSearchResult plugSearchResult = new PlugSearchResult();
        ArrayList<PlugSearchResult.Song> songs = new ArrayList<>();

        if (queue.equalsIgnoreCase("qq")) {
            APISearchResult musictype = qqMusicApiService.search(new APISearchParam().setKey(Keywords).setLimit(pagersize.toString()).setOffset(pageindex.toString()).setType(data.get("musictype")));
            if (musictype.getCode() == 0) {
                List<String> artists = new ArrayList<String>();
                APISearchResult.DataBean.SongBean song = musictype.getData().getSong();
                song.getList().forEach(iteam -> {
                    List<APISearchResult.DataBean.SongBean.ListBean.SingerBean> singer = iteam.getSinger();
                    singer.forEach(sin -> {
                        artists.add(sin.getName());
                    });
                    songs.add(new PlugSearchResult.Song().setId(iteam.getSongmid()).setMusicName(iteam.getSongname()).setMusicImage(WPMusicApiConstantQQ.ALBUM + iteam.getSongmid() + ".jpg")
                            .setMusicAlbum(iteam.getAlbumname()).setMusicArtists(Join.join(",", artists)).setPlugName("WPMuiscApi-qq"));
                });
                return plugSearchResult.setPlugName("WPMuiscApi-qq").setPlugMusicSearchSize(song.getCurnum()).setPlugMusicSearchIndex(song.getCurpage()).setPlugMusicSearchCount(song.getTotalnum()).setSongs(songs);
            }
            throw new PlugError("插件搜索错误");


        } else if (queue.equalsIgnoreCase("kw")) {
            cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APISearchResult search = kwMusicApiService.search(new cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APISearchParam().setKey(Keywords).setLimit(pagersize.toString()).setOffset(pageindex.toString()));
            if (search.getCode() == 200) {
                search.getData().getList().forEach(iteam -> {
                    songs.add(new PlugSearchResult.Song().setPlugName("WPMuiscApi-kw").setMusicName(iteam.getName()).setMusicImage(iteam.getPic())
                            .setMusicAlbum(iteam.getAlbum()).setMusicArtists(iteam.getArtist()).setId(iteam.getRid() + ""));
                });
                return plugSearchResult.setPlugName("WPMuiscApi-kw").setPlugMusicSearchCount(search.getData().getTotal()).setPlugMusicSearchCount(search.getData().getTotal()).setPlugMusicSearchSize(pagersize.longValue()).setPlugMusicSearchIndex(pageindex.longValue()).setSongs(songs);
            }
            throw new PlugError("插件搜索错误");
        } else if (queue.equalsIgnoreCase("kg")) {
            cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APISearchResult search = kgMusicApiService.search(new cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APISearchParam().setKey(Keywords).setLimit(pagersize.toString()).setOffset(pageindex.toString()));
            if (search.getError_code() == 0) {
                search.getData().getLists().forEach(iteam -> {
                    songs.add(new PlugSearchResult.Song().setMusicName(iteam.getSongName()).setMusicArtists(iteam.getSingerName())
                            .setMusicAlbum(iteam.getAlbumName()).setPlugName("WPMuiscApi-kg").setId(iteam.getAlbumID()).setMusicImage(kgMusicApiService.download(new cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APIDownloadParam().setHash(iteam.getFileHash()).setAid(iteam.getAlbumID())).getData().getImg()).setPlugData(new HashMap<String, String>() {{
                                put("aid", iteam.getAlbumID());
                                put("hash", iteam.getFileHash());
                            }}));
                });
                return plugSearchResult.setPlugName("WPMuiscApi-kg").setPlugMusicSearchCount(search.getData().getTotal()).setPlugMusicSearchSize(search.getData().getPagesize()).setPlugMusicSearchIndex(search.getData().getPage()).setSongs(songs).setPlugMusicSearchCount(search.getData().getTotal());
            }
            throw new PlugError("插件搜索错误");
        } else {
            throw new PlugError("插件通道错误，通道支持QQ，KG,KW");
        }
    }

    @Override
    public SqMusic musicDownload(DownloadParam downloadParam) throws PlugError {
        String plugName = downloadParam.getPlugData().get("queue");
        String setVlaue = null;
        String url = null;
        String fileName = null;
        String lyircValue = null;
        String lyirctrans = null;
        String sourImageUrl=null;
        if (plugName.equalsIgnoreCase("qq")) {
            APIDownloadResult download = qqMusicApiService.download(new APIDownloadParam().setBr(downloadParam.getBr()).setMid(downloadParam.getId()));
            url = download.getData().getUrl();
            //是否需要下载歌词
            if (downloadParam.isDownliadMusicLyric()) {
                APILyircResult lyric = qqMusicApiService.lyric(new APILyircParam().setMid(downloadParam.getId()));
                lyircValue = lyric.getLyric();
                lyirctrans = lyric.getTrans();
            }

        } else if (plugName.equalsIgnoreCase("kw")) {
            cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APIDownloadResult download = kwMusicApiService.download(new cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APIDownloadParam().setRid(downloadParam.getId()).setBr(downloadParam.getBr()));
            url = download.getUrl();
            if (downloadParam.isDownliadMusicLyric()) {
                cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APILyircResult lyric = kwMusicApiService.lyric(new cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APILyircParam().setRid(downloadParam.getId()));

                lyircValue = lyric.getLyric_str();
                // lyirctrans=lyric.getTrans();
            }

        } else if (plugName.equalsIgnoreCase("kg")) {
            HashMap<String, String> plugData = downloadParam.getPlugData();
            cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APIDownloadResult download = kgMusicApiService.download(new cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APIDownloadParam().setAid(plugData.get("aid")).setHash(plugData.get("hash")));
            url = download.getData().getPlay_url();
            if (downloadParam.isDownliadMusicLyric()) {
                lyircValue = download.getData().getLyrics();
                //                lyirctrans=lyric.getTrans();
            }
        }
//            是否缓存下载
        if (downloadParam.isTemp()) {
            //临时缓存
            setVlaue = SQConstant.SYSTEM_TEMPDOWNLOAD_DIR;

        } else {
            setVlaue = SQConstant.SYSTEM_DOWNLOAD_DIR;
            try {
                fileName = FileUtil.downloadToFile(url, setVlaue, downloadParam.getMusicName() + "-" + downloadParam.getMusicArtists());
            } catch (Exception e) {
                log.error("插件运行异常："+e.getMessage());
                throw new PlugError("插件运行io异常");
            }
        }

        //是否下载图片
        //是否下载图片
        String musicImage =null;
        if (downloadParam.isDownliadMusicImage()) {
//            musicImage= downloadParam.getMusicImage();
            try {
                musicImage=FileUtil.downloadToFile(downloadParam.getMusicImage(), SQConstant.SYSTEM_TEMPDOWNLOAD_DIR   );
//                downloadParam.setMusicImage(FileUtil.downloadToFile(musicImage, SQConstant.SYSTEM_DOWNLOAD_DIR));
            } catch (Exception e) {
                log.error("wp插件在下载中失败原因：" + e.getMessage());
            }
        }
        SqMusic sqMusic = new SqMusic()
                .setMusicName(downloadParam.getMusicName())
                .setMusicAlbum(downloadParam.getMusicAlbum())
                .setMusicArtists(downloadParam.getMusicArtists())
                .setMusicDescribe(downloadParam.getMusicDescribe())
                .setMusicTime(LocalDateTime.now())
                .setMusicImage(musicImage)
                .setMusicSourImageUrl(downloadParam.getMusicImage())
                .setMusicType(plugName)
                .setMusicPath(fileName)
                .setMusicLyricTrans(lyirctrans)
                .setMusicLyric(lyircValue);


        if (!downloadParam.isTemp()) {
            sqMusic.setMusicCodeType(FileUtil.getFileSuffix(fileName).replaceAll(".", ""));
            musicService.save(sqMusic);
        }else{
            sqMusic.setMusicPath(url);
        }
        return sqMusic;


//        throw new  PlugError("插件通道错误，通道支持wp-qq，wp-kw,wp-kg");
    }

    @Override
    public PlugLyicResult MusiclyricDownload(LyricParam lyricParam) throws PlugError {
        String plugName =  lyricParam.getPlugData().get("queue");
        if (plugName.equalsIgnoreCase("qq")) {
            APILyircResult lyric = qqMusicApiService.lyric(new APILyircParam().setMid(lyricParam.getId()));
            return new PlugLyicResult().setLyric(lyric.getLyric()).setTrans(lyric.getTrans());
        } else if (plugName.equalsIgnoreCase("wk")) {
            cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APILyircResult lyric = kwMusicApiService.lyric(new cn.sq.musicserver.plug.model.wpmusicapi.kw.entity.APILyircParam().setRid(lyricParam.getId()));
            return new PlugLyicResult().setLyric(lyric.getLyric_str());
        } else if (plugName.equalsIgnoreCase("wg")) {
            cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APIDownloadResult lyric = kgMusicApiService.lyric(new cn.sq.musicserver.plug.model.wpmusicapi.kg.entity.APIDownloadParam().setAid(lyricParam.getPlugData().get("aid")).setHash(lyricParam.getPlugData().get("hash")));
            return new PlugLyicResult().setLyric(lyric.getData().getLyrics());
        } else {
            throw new PlugError("插件通道错误，通道支持qq，kw,kg");
        }
    }
}
